﻿using System.Collections;
using System.Collections.Generic;
using System.Data;
using AutoMapper;

namespace AutoMapperHelpLibrary
{
    /// <summary>
    /// AutoMapper扩展帮助类
    /// </summary>
    public static class AutoMapperHelper
    {
        /// <summary>
        /// 类型映射（将源对象转成目标对象）
        /// </summary>
        /// <typeparam name="T">目标类</typeparam>
        /// <param name="obj">待映射类</param>
        /// <returns></returns>
        public static T MapTo<T>(this object obj)
        {
            if (obj==null)
            {
                return default(T);
            }
            Mapper.CreateMap(obj.GetType(), typeof (T));
            return Mapper.Map<T>(obj);
        }
        /// <summary>
        /// 集合列表类型映射
        /// </summary>
        /// <typeparam name="TDestination">目标集合</typeparam>
        /// <param name="source">待映射集合</param>
        /// <returns></returns>
        public static List<TDestination> MapToList<TDestination>(this IEnumerable source)
        {
            foreach (var item in source)
            {
                var type = item.GetType();
                Mapper.CreateMap(type, typeof(TDestination));
                break;
            }
            return Mapper.Map<List<TDestination>>(source);
        }
        /// <summary>
        /// 集合列表类型映射
        /// </summary>
        public static List<TDestination> MapToList<TSource, TDestination>(this IEnumerable<TSource> source)
        {
            //IEnumerable<T> 类型需要创建元素的映射
            Mapper.CreateMap<TSource, TDestination>();
            return Mapper.Map<List<TDestination>>(source);
        }
        /// <summary>
        /// 类型映射(将源数据对象中的数据替换到目标对象。一般用于修改数据)
        /// </summary>
        /// <typeparam name="TSource">源数据类</typeparam>
        /// <typeparam name="TDestination">目标类</typeparam>
        /// <param name="source">源数据对象</param>
        /// <param name="destination">目标对象</param>
        /// <returns></returns>
        public static TDestination MapTo<TSource, TDestination>(this TSource source, TDestination destination)
            where TSource : class
            where TDestination : class
        {
            if (source == null) return destination;
            Mapper.CreateMap<TSource, TDestination>();
            return Mapper.Map(source, destination);
        }
        /// <summary>
        /// DataReader映射
        /// </summary>
        public static IEnumerable<T> DataReaderMapTo<T>(this IDataReader reader)
        {
            Mapper.Reset();
            Mapper.CreateMap<IDataReader, IEnumerable<T>>();
            return Mapper.Map<IDataReader, IEnumerable<T>>(reader);
        }
    }
}
